/*
 * @Author: tangjianjie 1663446974@qq.com
 * @Date: 2024-12-12 15:45:14
 * @LastEditors: tangjianjie 1663446974@qq.com
 * @LastEditTime: 2024-12-17 11:23:00
 * @FilePath: \v3-shopping\server\controllers\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 打造一个可以连接数据库的方法

// 导入模块
const mysql = require("mysql2/promise");
const { database } = require("../config/index.js");

// 创建连接池
const pool = mysql.createPool({
  host: database.HOST,
  user: database.USERNAME,
  password: database.PASSWORD,
  database: database.DATABASE,
  port: database.PORT,
});

// 可以连接数据库的方法
const allService = {
  async query(sql) {
    try {
      // 通过连接池来创建连接
      const conn = await pool.getConnection();
      // 对该连接执行某些操作
      const [rows, err] = await conn.query(sql);

      // 不要忘记释放连接！
      pool.releaseConnection(conn);

      return Promise.resolve(rows);
    } catch (error) {
      return Promise.reject(error);
    }
  },
};

// 登录
const userLogin = (username, password) => {
  const _sql = `select * from users where username="${username}" and password="${password}";`;
  return allService.query(_sql);
};

// 查找账号
const userFind = (username) => {
  const _sql = `select * from users where username="${username}"`;
  return allService.query(_sql);
};

// 注册
const userRegister = (values) => {
  const _sql = `insert into users (username, password, nickname) values ("${values.username}", "${values.password}", "${values.nickname}");`;
  return allService.query(_sql);
};

// 查找商品
const findShop = () => {
  const _sql = `select * from shop`;
  return allService.query(_sql);
};

module.exports = {
  userLogin,
  userFind,
  userRegister,
  findShop,
};
